package com.ltmonitor.web.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.ltmonitor.web.util.OnlineUser;

public class LoginInterceptor extends HandlerInterceptorAdapter {
	private static final String[] IGNORE_URI = { "/login.action","/logout.action","/randomPicture.action" };

	public static final String ONLINE_USER = "currUserInfo";
	 private static final String LOGIN_URL = "/logout.action";  

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		String url = request.getRequestURL().toString();
		for (String s : IGNORE_URI) {
			if (url.contains(s)) {
				return true;
			}
		}
		
		if(url.indexOf(".action") > 0)
		{
			OnlineUser user = (OnlineUser) request.getSession().getAttribute(
					ONLINE_USER);
			
			if(user == null)
			{
				response.sendRedirect(request.getContextPath() + LOGIN_URL);  
				return false;
			}
		}

		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		super.postHandle(request, response, handler, modelAndView);
	}

}
